<template>
  <div class="">
    <div class="b-f p-d">
      <el-tabs v-model="queryString.activeName" @tab-click="handleClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane label="共享资源目录" name="sharing"></el-tab-pane>
        <el-tab-pane label="不共享资源目录" name="noShare"></el-tab-pane>
      </el-tabs>
      <div class="p-t">
        <SearchComp :searchForm="searchForm" :searchData="queryString" :searchAction="searchAction"></SearchComp>
      </div>
      <div class="p-t">
        <div class="btnStyle flex-between ">
          <div class="btnStyle flex-a-c ">
            <el-button class="m-l-5 m-r-5" size="small" type="primary" @click="addInstrument">新增</el-button>
            <el-button class="m-l-5 m-r-5" size="small" type="warning" @click="handleDownloadFile">一键导出</el-button>
            <el-upload class="m-l-5 m-r-5" action="#" :on-change="handleUploadFile" :show-file-list="false" :auto-upload="false">
              <el-button size="small" type="warning">一键导入</el-button>
            </el-upload>
            <el-button class="m-l-5 m-r-5" size="small" type="danger" @click="batchDelete">批量删除</el-button>
            <!-- <el-button size="small" type="warning">一键导入</el-button> -->
          </div>
        </div>
        <TableCompEle class="m-t" ref="multipleTable" :tableData="tableData" :tableConfig="tableConfig" :tableAction="tableAction" :isSelect="true"
          :isIndex="true" :isShowPage="true" :queryParams="queryParams" @getPagination="getList" @handleSelectionChange="handleSelectionChange">
          <template v-slot:fileImgList="row">
            <span>{{ row?.row?.fileImgList?.length??0 }}</span>
          </template>
          <template v-slot:fileList="row">
            <span>{{ row?.row?.fileList?.length??0 }}</span>
          </template>
        </TableCompEle>
      </div>
    </div>
    <div v-if="isSystemUp" class="wrap">
      <div class="proWrap">
        <div class="wordStyle">
          拼命加载中<span class="dot1"></span> <span class="dot2"></span><span class="dot3"></span>
        </div>
        <el-progress :text-inside="true" :stroke-width="35" :percentage="percentage"></el-progress>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getInstrumentList,
  deleteInstrumentBatch,
  updateInstrument,
  downloadMultiple,
  uploadMultiple
  // updateFacilities
} from '@/api/yqgx/instrument'
export default {
  data() {
    return {
      isSystemUp: false,
      percentage: 0,
      timer: null,
      activeName: 'all',
      multipleSelection: [],
      queryParams: {
        total: 20,
        currentPage: 1,
        pageSize: 10,
        type: ''
      },
      tableData: [
      ],
      tableConfig: [
        {
          prop: 'instrumentNum',
          label: '资产编号'
        },
        {
          prop: 'instrumentNameCn',
          label: '仪器设备名称',
          isLink: true,
          type: 'primary',
          method: row => {
            this.$router.push({
              name: 'instrumentInfo',
              params: { flag: 'look', id: row.id }
            })
          }
        },
        {
          prop: 'type',
          label: '仪器设备来源'
        },
        {
          prop: 'instrumentClassifyNum',
          label: '设备分类'
        },
        // {
        //   prop: 'managementUnit',
        //   label: '管理单位'
        // },
        // {
        //   prop: 'originValue',
        //   label: '原值(万元)'
        // },
        {
          prop: 'sharedScope',
          label: '共享范围'
        },
        {
          prop: 'fileImgList',
          label: '图片数量',
          isSlot: true
        },
        {
          prop: 'fileList',
          label: '资料数量',
          isSlot: true
        },
        {
          prop: 'ReportTime',
          label: '上报时间'
        },
        {
          label: '状态',
          prop: 'showReport',
          width: '150px',
          isStatus: row => {
            // switch (row.status) {
            //   case 1: // 待上报
            //     return { color: 'blue', bgColor: 'blue-bg' }
            //   case 2: // 待审核
            //     return { color: 'green', bgColor: 'green-bg' }
            //   default: // 审核通过已上报
            //     return { color: 'red', bgColor: 'red-bg' }
            // }
            switch (row.showReport) {
              case '待上报': // 待上报
                return { color: 'blue', bgColor: 'blue-bg' }
              default: // 已上报
                return { color: 'green', bgColor: 'green-bg' }
            }
          }
        }
      ],
      tableAction: {
        align: () => 'center',
        width: () => String(220),
        operations: [
          {
            label: '查看',
            isLink: true,
            type: 'primary',
            method: row => {
              this.$router.push({
                name: 'instrumentInfo',
                params: { flag: 'look', id: row.id }
              })
            }
          },
          {
            label: '上报',
            isLink: true,
            type: 'primary',
            isShow: (row) => {
              return !row.Report
            },
            method: row => {
              this.handleReport(row, '待审核')
              row['isAlert'] = true
              localStorage.setItem('alertList', JSON.stringify(row))
            }
          },
          {
            label: '修改',
            isLink: true,
            type: 'primary',
            // isShow: (row) => {
            //   return !row.Report
            // },
            method: row => {
              this.$router.push({
                name: 'instrumentInfo',
                params: { flag: 'edit', id: row.id }
              })
            }
          },
          {
            label: '下载',
            isLink: true,
            type: 'primary',
            method: row => {
              this.downloadFun([row.id])
            }
          },
          {
            label: '删除',
            isLink: true,
            isShow: (row) => {
              return !row.Report
            },
            type: 'danger',
            method: row => {
              this.deleteFun([row.id])
            }
          }
        ]
      },
      queryString: {
        name: '',
        activeName: 'all'
      },
      searchForm: {
        changeMethod: () => {
          this.queryParams.currentPage = 1
        },
        formData: [
          {
            type: 'Input',
            label: '仪器设备名称',
            prop: 'instrumentNameCn',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入'
          },
          {
            type: 'Input',
            label: '仪器设备来源',
            prop: 'type',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入'
          },
          {
            type: 'Input',
            label: '所属大单位',
            prop: 'managementUnit',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入'
          }
        ]
      },
      searchAction: [
        {
          label: '查询',
          type: 'primary',
          handle: () => {
            this.queryParams.currentPage = 1
            this.$refs.multipleTable.clearSelection()
          }
        },
        {
          label: '重置',
          type: 'primary',
          plain: true,
          handle: () => {
            this.queryString = {
              instrumentNameCn: '',
              type: '',
              managementUnit: '',
              activeName: this.queryString.activeName
            }
            this.queryParams.currentPage = 1
          }
        }
      ]
    }
  },
  created() {
    this.getList()

  },
  methods: {
    addInstrument() {
      this.$router.push({
        name: 'instrumentInfo',
        params: { flag: 'add' }
      })
    },
    handleDownloadFile() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择要导出的数据'
        })
        return
      }
      const ids = []
      this.multipleSelection.forEach(items => {
        ids.push(items.id)
      })
      this.downloadFun(ids)
    },
    batchDelete() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      const ids = []
      this.multipleSelection.forEach(items => {
        ids.push(items.id)
      })
      this.deleteFun(ids)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleClick() {
      this.queryParams.type = this.queryString.activeName
      this.getList()
    },
    handleUploadFile(file) {
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadMultiple(formData).then(() => {
        this.$message.success("操作成功！")
        this.getList()
      })
    },
    getList() {
      getInstrumentList(this.queryParams).then((res) => {
        // this.tableData = res.data.slice(0, 4)
        res.data.forEach((item) => {
          if (!item.Report) {
            item.showReport = '待上报'
          } else {
            item.showReport = '已上报'
          }
        })
        this.tableData = res.data
        this.allData = this.tableData
        this.queryParams.total = res.total
      })
    },
    handleReport(row, status) {
      row.Report = status

      let currentDate = new Date();

      // 获取当前日期的年、月、日
      let year = currentDate.getFullYear();
      let month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 添加前导零
      let day = currentDate.getDate().toString().padStart(2, '0'); // 添加前导零
      // 构建当前日期的字符串形式（格式：YYYY-MM-DD）
      let currentDateStr = year + '-' + month + '-' + day;

      row.ReportTime = currentDateStr
      updateInstrument(row).then(() => {
        this.getList()
        this.$message.success("操作成功！")
      })
    },
    downloadFun(ids) {
      this.$confirm(`确定要导出吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.isSystemUp = true
          this.timer = setInterval(() => {
            if (this.percentage >= 100) {
              this.percentage = 100;
              this.isSystemUp = false
              this.$message.success("操作成功！")
              clearInterval(this.timer);
            } else {
              this.percentage += 10;
            }
          }, 200);
          downloadMultiple(ids)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    deleteFun(ids) {
      this.$confirm(`确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteInstrumentBatch(ids).then(() => {
            this.$refs.multipleTable.clearSelection()
            this.$message.success("操作成功！")
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
  },
  destroyed() {
    clearInterval(this.timer);
  },
}
</script>

<style lang="less" scoped>
  .wrap {
    position: absolute;
    width: 100%;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    // background: url('~@/assets/img/background.png');
    // background-size: cover;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    .proWrap {
      width: 100%;
      text-align: center;
    }
    .wordStyle {
      color: #fff;
    }
    ::v-deep(.el-progress) {
      width: 50% !important;
      margin: 0 auto;
    }
  }
</style>